package com.cqc.networkmanager01;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private boolean connected;
    private NetworkInfo activeNetworkInfo;
    private ConnectivityManager manager;
    private IntentFilter filter;
    private ConnectChangeReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);


        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                activeNetworkInfo = manager.getActiveNetworkInfo();
                if (activeNetworkInfo != null) {
                    connected = activeNetworkInfo.isConnected();
                    Log.d(TAG, "connected=" + connected);
                } else {
                    Log.d(TAG, "connected==false");
                }
            }
        });


        Button btn2 = (Button) findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (wifiInfo.isConnected() || mobileInfo.isConnected()) {
                    Log.d(TAG, "联网正常");
                } else {
                    Log.d(TAG, "联网失败");
                }
                Log.d(TAG, "wifiInfo.isConnected()=" + wifiInfo.isConnected() + ",mobileInfo.isConnected()" + mobileInfo.isConnected());
            }
        });

        CheckBox cb1 = (CheckBox) findViewById(R.id.cb1);

        filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new ConnectChangeReceiver();
        cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    registerReceiver(receiver, filter);
                } else {
                    unregisterReceiver(receiver);
                }
            }
        });
    }
}

